<?php

namespace addons\yalimedia\library;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Kms\Kms;
use AlibabaCloud\Vod\Vod;
use fast\Tree;

/**
 * AlibabaClound服务类
 */
class AlibabaCloundHelper
{
    public static $_instance;
    private static $accessKeyId;
    private static $accessKeySecret;
    private static $client;
    private static $regionId;
    public static function instance()
    {
        if(!self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $yalimedia = get_addon_config('yalimedia');
        $config = $yalimedia['ali'];
        self::$accessKeyId = $config['accessKeyId'];
        self::$accessKeySecret = $config['accessKeySecret'];
        self::$client = "AliyunVodClient";
        self::$regionId = $config['regionId'];
        self::initVodClient(self::$accessKeyId,self::$accessKeySecret);
    }

    private static function initVodClient($accessKeyId, $accessKeySecret) {
        $regionId = self::$regionId;  // 点播服务接入区域
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
            ->regionId($regionId)
            ->connectTimeout(1)
            ->timeout(3)
            ->name(self::$client);
    }

    /**
     * 添加分类
     */
    public function add_category($catename,$parentid){
        $result = Vod::v20170321()
            ->addCategory()
            ->withCateName($catename)
            ->withParentId($parentid)
            ->client(self::$client)
            ->request();

        if(!empty($result->Category->CateId)){
            return $result->Category->CateId;
        }else{
            return 0;
        }
    }

    /**
     * 编辑分类
     */
    public function edit_category($CateId,$CateName){
        try {
            $result = Vod::v20170321()
                ->updateCategory()
                ->withCateId($CateId)
                ->withCateName($CateName)
                ->client(self::$client)
                ->request();
            if(!empty($result->RequestId)){
                return true;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }

    }

    /**
     * 获取分类
     * @param $cateId
     * @return array|mixed|null
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    public  function categorie($cateId){
        $result = Vod::v20170321()
            ->getCategories()
            ->withCateId($cateId)
            ->client(self::$client)
            ->request();

        if(!empty($result->Category)){
            return $result->Category;
        }else{
            return [];
        }
    }

    /**
     * 获取下级分类
     */
    public  function categories($cateId="-1"){
        $result = Vod::v20170321()
            ->getCategories()
            ->withCateId($cateId)
            ->withPageSize(100)
            ->client(self::$client)
            ->request();
        if(!empty($result->SubCategories->Category)){
            return $result->SubCategories->Category;
        }else{
            return [];
        }
    }

    /**
     * 删除分类
     * @return int
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    public function del_category($cateId){
        $result = Vod::v20170321()
            ->deleteCategory()
            ->withCateId($cateId)
            ->client(self::$client)
            ->request();

        if(!empty($result->RequestId)){
            return true;
        }else{
            return false;
        }
    }

    public function searchMedia($type,$match,$page,$limit){
        try{
            $result = Vod::v20170321()
                ->SearchMedia()
                ->withSearchType($type)
                ->withMatch($match)
                ->withFields("Fields=Title,Title,CoverURL,URL,Size,Status,VideoId,CreationTime")
                ->withPageNo($page)
                ->withPageSize($limit)
                ->client(self::$client)
                ->request();


            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch(ServerException $e){
            return false;
        }
    }
    /**
     * 获取视频
     */
    public function videos($cateId,$page,$limit){

        try{
            $result = Vod::v20170321()
                ->GetVideoList()
                ->withStatus("Normal,Transcoding")
                ->withCateId($cateId)
                ->withPageNo($page)
                ->withPageSize($limit)
                ->client(self::$client)
                ->request();


            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch(ServerException $e){
            return false;
        }

    }

    /**
     * 获取图片详情
     */
    public function image($ImageId){
        try {
            $result = Vod::v20170321()
                ->GetImageInfo()
                ->withImageId($ImageId)
                ->withOutputType("cdn")
                ->client(self::$client)
                ->request();
            if(!empty($result->ImageInfo)){
                return $result->ImageInfo;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }

    }

    /**
     * 获取视频详情
     */
    public function video($videoid){
        try {
            $result = Vod::v20170321()
                ->GetVideoInfo()
                ->withVideoId($videoid)
                ->client(self::$client)
                ->request();
            if(!empty($result->Video)){
                return $result->Video;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }

    }

    /**
     * 编辑视频
     * @param $videoid
     * @param $cateid
     * @param $title
     * @return bool
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    public function edit_video($videoid,$cateid,$title){
        $result = Vod::v20170321()
            ->UpdateVideoInfo()
            ->withVideoId($videoid)
            ->withCateId($cateid)
            ->withTitle($title)
            ->client(self::$client)
            ->request();
        if(!empty($result->RequestId)){
            return true;
        }else{
            return false;
        }
    }

    /**
     *更新图片信息
     * @param $updateContent
     * @return bool
     * @throws ServerException
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function update_image($updateContent){
        $result = Vod::v20170321()
            ->UpdateImageInfos()
            ->withUpdateContent($updateContent)
            ->client(self::$client)
            ->request();
        if(!empty($result->RequestId)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除视频
     * @param $videoid
     */
    public function del_video($videoid){
        $result = Vod::v20170321()
            ->DeleteVideo()
            ->withVideoIds($videoid)
            ->client(self::$client)
            ->request();
        if(!empty($result->RequestId)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 删除图片
     */
    public function del_image($imageid){
        $result = Vod::v20170321()
            ->DeleteImage()
            ->withDeleteImageType("ImageId")
            ->withImageIds($imageid)
            ->client(self::$client)
            ->request();
        if(!empty($result->RequestId)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取播放详情
     * @param $videoid
     * @return \AlibabaCloud\Client\Result\Result|bool
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function GetPlayInfo($videoid){

        try {
            $result = Vod::v20170321()
                ->getPlayInfo()
                ->withVideoId($videoid)
                ->client(self::$client)
                ->request();

            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch (ServerException $e){

            return false;
        }

    }

    /**
     * 获取播放凭证
     * @param $videoid
     * @return \AlibabaCloud\Client\Result\Result|bool
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function getPlayAuth($videoid){
        try {
            $result = Vod::v20170321()
                ->getVideoPlayAuth()
                ->withVideoId($videoid)
                ->client(self::$client)
                ->request();
            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }
    }

    //获取图片上传地址和凭证
    public function createUploadImage($titleName,$cateId,$imageType="default"){
        try {

            $result = Vod::v20170321()
                ->CreateUploadImage()
                ->withTitle($titleName)
                ->withCateId($cateId)
                ->withImageType($imageType)
                ->client( self::$client)
                ->request();
            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }
    }

    public function createUploadVideo($titleName,$fileName,$cateId,$tempid=""){
        try {

            $result = Vod::v20170321()
                ->createUploadVideo()
                ->withTitle($titleName)
                ->withCateId($cateId)
                ->withFileName($fileName)
                ->withTemplateGroupId($tempid)
                ->client(self::$client)
                ->request();
            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }
    }

    public function RefreshUploadVideo($videoId){
        try {
            $result = Vod::v20170321()
                ->refreshUploadVideo()
                ->withVideoId($videoId)
                ->client(self::$client)
                ->request();
            if(!empty($result)){
                return $result;
            }else{
                return false;
            }
        }catch (ServerException $e){
            return false;
        }
    }


    public function transjob($tempid,$videoid){
        try {
            $result = Kms::v20160120()
                ->generateDataKey()
                ->withKeyId("d4945771-1ed6-4350-9771-8417a9674dc7")
                ->withKeySpec("AES_128")
                ->client(self::$client)
                ->request();

            if(!empty($result)){
                $CiphertextBlob = $result->CiphertextBlob;
            }else{
                return false;
            }

            $result = Vod::v20170321()
                ->submitTranscodeJobs()
                ->withTemplateGroupId($tempid)
                ->withVideoId($videoid)
                ->withEncryptConfig(json_encode(['CipherText'=>$CiphertextBlob,'KeyServiceType'=>'KMS','DecryptKeyUri'=>"http://decrypt.demo.com?CipherText=".$CiphertextBlob]))
                ->client(self::$client)
                ->request();

            if(!empty($result)){
                return $result;
            }else{
                return false;
            }

        }catch (ServerException $e){
            return false;
        }

    }


    public function getFilesize($num) {
        $p = 0;
        $format = 'bytes';
        if( $num > 0 && $num < 1024 ) {
            $p = 0;
            return number_format($num) . ' ' . $format;
        }
        if( $num >= 1024 && $num < pow(1024, 2) ){
            $p = 1;
            $format = 'KB';
        }
        if ( $num >= pow(1024, 2) && $num < pow(1024, 3) ) {
            $p = 2;
            $format = 'MB';
        }
        if ( $num >= pow(1024, 3) && $num < pow(1024, 4) ) {
            $p = 3;
            $format = 'GB';
        }
        if ( $num >= pow(1024, 4) && $num < pow(1024, 5) ) {
            $p = 3;
            $format = 'TB';
        }
        $num /= pow(1024, $p);
        return number_format($num, 2) . ' ' . $format;
    }


}
